package com.mzj.saas.jobs.lock.service;

import com.alibaba.druid.util.StringUtils;
import com.mzj.saas.commons.util.DateUtils;
import com.mzj.saas.jobs.backlog.entity.SmartLock;
import com.mzj.saas.jobs.backlog.repository.BacklogItemLockOffRepository;
import com.mzj.saas.jobs.backlog.repository.BacklogItemRepository;
import com.mzj.saas.jobs.lock.entity.HouseLockOpenStatistics;
import com.mzj.saas.jobs.lock.repository.HouseLockOpenStatisticsRepository;
import com.mzj.saas.jobs.lock.vo.LockOpenLogVO;
import com.mzj.saas.jobs.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LockService {
	private static Logger log = LoggerFactory.getLogger(LockService.class);

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private RedisService redisService;
	@Autowired
	private BacklogItemRepository backlogItemRepository;
	@Autowired
	private BacklogItemLockOffRepository backlogItemLockOffRepository;
	@Autowired
	private HouseLockOpenStatisticsRepository houseLockOpenStatisticsRepository;

	public String work() throws Exception {

		lockUnOpenTime();

		return "SUCCESS";
	}

	public void lockUnOpenTime() {
		try {
			log.info("lockUnOpenTime 统计智能锁未开门时间 start");

			String sql = "SELECT ol.lock_id AS lockId,ol.open_type AS openType,MAX(ol.open_time) AS openTime FROM saas_house_lock_open_log ol\n"
					+ "left join saas_smart_lock sl on ol.lock_id = sl.id \n"
					+ "WHERE ol.open_type = 1 and sl.id is not null GROUP BY ol.lock_id";

			List<LockOpenLogVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(LockOpenLogVO.class));
			for (LockOpenLogVO vo : list) {
				Long lockId = vo.getLockId();
				Integer openType = vo.getOpenType();// 1外开门 2内开门
				String openTime = DateUtils.format(vo.getOpenTime(), DateUtils.FORMAT_DATETIME_14,
						DateUtils.FORMAT_DATETIME_14);
				Integer openDay = DateUtils.getDataDifferenceDay(openTime);

				HouseLockOpenStatistics houseLockOpenStatistics = houseLockOpenStatisticsRepository
						.findByLockIdAndType(lockId, openType);
				if (houseLockOpenStatistics == null) {
					HouseLockOpenStatistics statistics = new HouseLockOpenStatistics();
					statistics.setLockId(lockId);
					statistics.setType(openType);
					statistics.setOpenDay(openDay);
					houseLockOpenStatisticsRepository.save(statistics);
				} else {
					houseLockOpenStatistics.setOpenDay(openDay);
					houseLockOpenStatisticsRepository.save(houseLockOpenStatistics);
				}
			}

			log.info("lockUnOpenTime 统计智能锁未开门时间  end");
		} catch (Exception e) {
			log.error("统计智能锁未开门时间" + e.getMessage(), e);
		}
	}

	/**
	 * 心跳状态验证
	 * 
	 * @author shun
	 * @date 2022年7月22日
	 */
	public void heartbeatStatus() {
		// 获取所有三代锁
		String sql = "SELECT * FROM saas_smart_lock lk WHERE lk.brand_id = 3";
		List<SmartLock> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SmartLock.class));

		for (SmartLock smartLock : list) {
			String value = redisService.getLockheartbeatStatusRedis(smartLock.getMac());
			if (StringUtils.isEmpty(value)) {
				log.info("智能锁离线, mac={}", smartLock.getMac());
				// 离线
				String update = "update saas_smart_lock set online_status = 0 where mac = ?";
				jdbcTemplate.update(update, smartLock.getMac());

				// 2022-08-22应客户要求，不推送离线告警
				/*String sqlRecord = "SELECT t.id FROM saas_backlog_item t WHERE t.house_id = ? AND t.type = ? AND DATE_FORMAT(t.create_time, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d')";
				List<BacklogItem> listRecord = jdbcTemplate.query(sqlRecord, new BeanPropertyRowMapper<>(BacklogItem.class), smartLock.getHouseId(), BacklogItemTypeEnum.LOCK_UNLINE.getValue());
				if(!listRecord.isEmpty()){
					log.info("当天已存在离线待办事项，不在推送，houseId={}", smartLock.getHouseId());
					continue;
				}
				// 推送离线告警
				String content = smartLock.getCommunityName() + smartLock.getUnitName() + smartLock.getBuildName()
						+ smartLock.getRoomNumber();
				// 代办事项
				BacklogItem item = new BacklogItem();
				item.setHouseId(smartLock.getHouseId());
				item.setOrgId(smartLock.getOrgId());
				item.setTitle("门锁离线告警");
				item.setContent(content);
				item.setBusinessStatus("门锁离线告警");
				item.setType(BacklogItemTypeEnum.LOCK_UNLINE.getValue());
				item.setHandleStatus(0);
				item.setMatchUserId(smartLock.getMatchUserId());
				if (!StringUtils.isEmpty(smartLock.getMatchUserId())) {
					String userSql = "SELECT * FROM saas_app_user au WHERE id = ? OR enterprise_user_id = ?";
					List<AppUser> appUserList = jdbcTemplate.query(userSql, new BeanPropertyRowMapper<>(AppUser.class),
							smartLock.getMatchUserId(), smartLock.getMatchUserId());
					if (!appUserList.isEmpty()) {
						item.setPhone(appUserList.get(0).getPhone());
					}
				} else {
					String chuSql = "SELECT * FROM saas_community_house_user hu WHERE hu.community_house_id = ? AND hu.status = ? AND hu.type = ?";
					List<CommunityHouseUser> chuList = jdbcTemplate.query(chuSql,
							new BeanPropertyRowMapper<>(CommunityHouseUser.class), smartLock.getHouseId(), 1, 1);
					if (!chuList.isEmpty()) {
						item.setMatchUserId(chuList.get(0).getUserId()); // 承租人ID
						item.setPhone(chuList.get(0).getMobile());// 电话
					}
				}
				item.setCreateTime(new Date());
				backlogItemRepository.save(item);

				// 门锁离线-待办事项参数数据
				BacklogItemLockOff lockoff = new BacklogItemLockOff();
				lockoff.setBacklogItemId(item.getId());
				lockoff.setLockId(smartLock.getId());
				lockoff.setMatchUserId(smartLock.getMatchUserId());
				backlogItemLockOffRepository.save(lockoff);*/
			}
		}
	}
}
